<template>
  <div>
    <header-view/>
    <div id="page-content" class="single-page">
      <div class="container container_detail">
        <div class="row" style="margin: 15px 25px; ">
          <div id="main-content" class="col-md-12">
            <div class="row">
              <div class="col-md-8 col-sm-12" style="padding-left: 3px; padding-right: 0px;">
                <d-player class="dplayer-div" v-if="dplayerFlag" ref="player"
                          :video="video"
                          :autoplay="dplayerProps.autoplay"
                          :lang="dplayerProps.lang"
                          :theme="dplayerProps.theme"
                          :danmaku="dplayerProps.danmaku"
                          :apiBackend="dplayerProps.apiBackend"
                          :logo="dplayerProps.logo"
                          :contextmenu="contextmenu"></d-player>
                <iframe v-if="!dplayerFlag" name="videoName" id="videoIframe" width="100%" height="650"
                        :src="video.liveServer == null ? videoLiveServerDefault : video.liveServer "
                        frameborder="0"
                        allowfullscreen></iframe>
              </div>
              <div class="col-md-4 col-sm-12 phoneStyle">
                <div id="sidebar">
                  <!--聊天tab-->
                  <el-tabs stretch="true" type="border-card" v-model="activeName" @tab-click="handleClick">
                    <el-tab-pane label="聊天" name="chat">
                      <div class="talk_con">
                        <div class="talk_show other_chat_div" id="words_chat">

                        </div>
                        <div class="talk_input">
                          <el-row class="messageRow">
                            <el-input type="text" class="bantxt" id="chatText" v-model="chatMessage"
                                      @keyup.enter.native="sendChat('')" placeholder="添加您的评论.."
                            ></el-input>
                            <emotion @emotion="handleEmotion" v-if="iEmotion" :height="200"></emotion>
                            <img src="../../static/images/biaoqing1.png" class="emotionChat" id="biaotitle"
                                 @click="toggloEmotion"
                                 alt="表情">
                            <button class="btn banbutt" type="button" id="seobut" @click="sendChat('')"><i
                              class="fa fa-chevron-circle-right"></i>发送
                            </button>
                          </el-row>
                        </div>
                      </div>

                    </el-tab-pane>
                    <el-tab-pane label="提问" name="question">
                      <div class="talk_con">
                        <div class="talk_show other_question_div" id="words_question">
                        </div>
                        <div class="talk_input">
                          <el-row class="messageRow">
                            <el-input type="text" class="bantxt" v-model="answerMessage"
                                      @keyup.enter.native="sendQuestion" placeholder="添加您的提问.."
                            ></el-input>
                            <el-button type="success" class="  btn banbutt" @click="sendQuestion"><i
                              class="fa fa-chevron-circle-right"></i>发送
                            </el-button>
                          </el-row>
                        </div>
                      </div>
                    </el-tab-pane>
                    <div style="height: 42px"></div>
                  </el-tabs>
                  <!---- 热门排行---->
                  <!--<div class="widget wid-news">
                    <div class="heading"><h4><i class="fa fa-clock-o"></i> 最新视频</h4></div>
                    <div class="content">
                      <div class="wrap-vid" v-for="(video,index) in videoFormData.newLasted" :index="''" :key="index">
                        <div class="zoom-container">
                          <div class="zoom-caption">
                            <span
                              v-bind:class="{ huikan : (video.type == 1 || video.type == 2) }">{{ video.liveStatusName }}</span>
                            <a href="javascript:void(0)" @click="toDetail(video)">
                              <i class="fa fa-play-circle-o fa-5x" style="color: #fff"></i>
                            </a>
                            <p>{{ video.title }}</p>
                          </div>
                          <img :src="video.liveCenterImg"/>
                        </div>
                        <h3 class="vid-name"><a href="#">{{ video.title }}</a></h3>
                        <div class="info">
                          <h5>主播：<a href="javascript:void(0)">{{video.anchorName }}</a></h5>
                          <span><i class="fa fa-calendar"></i>{{ $moment(video.liveTime).format('YYYY-MM-DD HH:MM:SS') }}</span>
                        </div>
                      </div>
                    </div>
                  </div>-->
                </div>
              </div>
            </div>
            <div class="line"></div>
            <div class="row">
              <div class="col-sm-12">
                <h4 class="vid-name">{{video.title}}</h4>
                <div class="info">
                  <br>
                  <h5> 直播人: <a href="#">{{ video.anchorName }}</a></h5>
                  <h5>直播时间:&nbsp; <i class="fa fa-calendar"></i>{{ $moment(video.liveTime).format('YYYY-MM-DD HH:mm:ss')
                    }}</h5>
                  <!--<span><i class="fa fa-heart"></i>1,200</span>-->
                  <h5> 当前在线人数: {{ onlinePersonNum}}</h5>
                </div>
                <br>
                <h4>节目简介</h4>
                <p style="margin-top: 20px"> {{ video.liveInfo }}</p>
              </div>
            </div>
            <!--相关视频-->
            <!-- <div class="box">
              <div class="box-header">
                <h2><i class="fa fa-globe"></i>相关视频</h2>
              </div>
              <div class="box-content">
                <div class="row">
                  <div class="col-md-4">
                    <div class="wrap-vid">
                      <div class="zoom-container">
                        <div class="zoom-caption">
                          <span>Video's Tag</span>
                          <a href="single.html">
                            <i class="fa fa-play-circle-o fa-5x" style="color: #fff"></i>
                          </a>
                          <p>Video's Name</p>
                        </div>
                        <img src="../../static/images/7.jpg"/>
                      </div>
                      <h3 class="vid-name"><a href="#">Video's Name</a></h3>
                      <div class="info">
                        <h5>By <a href="#">Kelvin</a></h5>
                        <span><i class="fa fa-calendar"></i>25/3/2015</span>
                        <span><i class="fa fa-heart"></i>1,200</span>
                      </div>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="wrap-vid">
                      <div class="zoom-container">
                        <div class="zoom-caption">
                          <span>Video's Tag</span>
                          <a href="single.html">
                            <i class="fa fa-play-circle-o fa-5x" style="color: #fff"></i>
                          </a>
                          <p>Video's Name</p>
                        </div>
                        <img src="../../static/images/8.jpg"/>
                      </div>
                      <h3 class="vid-name"><a href="#">Video's Name</a></h3>
                      <div class="info">
                        <h5>By <a href="#">Kelvin</a></h5>
                        <span><i class="fa fa-calendar"></i>25/3/2015</span>
                        <span><i class="fa fa-heart"></i>1,200</span>
                      </div>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="wrap-vid">
                      <div class="zoom-container">
                        <div class="zoom-caption">
                          <span>Video's Tag</span>
                          <a href="single.html">
                            <i class="fa fa-play-circle-o fa-5x" style="color: #fff"></i>
                          </a>
                          <p>Video's Name</p>
                        </div>
                        <img src="../../static/images/9.jpg"/>
                      </div>
                      <h3 class="vid-name"><a href="#">Video's Name</a></h3>
                      <div class="info">
                        <h5>By <a href="#">Kelvin</a></h5>
                        <span><i class="fa fa-calendar"></i>25/3/2015</span>
                        <span><i class="fa fa-heart"></i>1,200</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>-->
          </div>
        </div>
      </div>
    </div>
    <footer-view/>
  </div>

</template>
<script>
  import {defaultHls} from '../assets/common/defaultHls'
  import {emotionList} from '../assets/common/emotionList'
  import headerView from '@/components/Header/index'
  import footerView from '@/components/Footer/index'
  import {chatAPI, videoAPI} from '../api/index'

  import {Notification} from 'element-ui'
  import urlUtil from '../assets/util/urlUtil'
  import VueDPlayer from './vueDplayerHls'
  import Emotion from '@/components/Emotion/index'
  import axo from 'axios'
  // import returnCitySN from 'returnCitySN' // 新浪 获取设备IP

  export default {
    name: 'detail',
    data () {
      return {
        loginUser: {
          uid: this.$root.uid,
          username: this.$root.username,
          email: this.$root.email
        },
        activeName: 'chat',
        answerMessage: '', // 提问回答
        chatMessage: '', // 聊天
        msg: 'Welcome to Your Vue.js App',
        dplayerFlag: false,
        video: {
          liveNo: this.$route.query.liveNo == null ? urlUtil.getUrlKey('liveNo') : this.$route.query.liveNo,
          quality: [
            {
              name: '高清',
              url: 'api/live/cctv1_2/index.m3u8', // this.video.quality[0].url,
              type: 'hls'// this.video.quality[0].type,
            },
            {
              name: '清晰',
              url: 'api/live/cctv1_2/index.m3u8', // this.video.quality[1].url,
              type: 'hls'// this.video.quality[1].type,
            },
          ],
          live: false,
          defaultQuality: 0,
          pic: 'https://www.baidu.com/img/pcpad_e247c0f9a461b6394da20e308588818f.png', // 首次显示的图片
          // thumbnails: 'https://www.baidu.com/img/pcpad_e247c0f9a461b6394da20e308588818f.png', //视频缩略图
          customType: {
            customFlv: function (video, player) {
              const flvPlayer = flvjs.createPlayer({
                type: 'flv',
                url: this.video.src,
              })
              flvPlayer.attachMediaElement(video)
              flvPlayer.load()
            },
          },
        },
        dplayerProps: {
          autoplay: false,
          theme: '#b7daff',
          lang: 'zh-cn',
          danmaku: true,
          apiBackend: {
            read: function (endpoint, callback) { // 这里和官方说的有点出入，因为这里是vue版本，可能不太一样，通过debug发现，只能这样去实现弹幕
              // 这里选择不从websocket服务器渲染，而是手动解耦渲染
              try {
                endpoint.success()
              } catch (e) {
              } // 消除弹幕加载中一直会提示问题，手动执行加载成功
            },
            send: function (endpoint, danmakuData, callback) { // danmakuData 竟然是undefined
              window.$$$video.sendChat(endpoint.data.text)
            }
          },
          logo: ''
        },
        danmuInit: false, // 是否在初始化视频时渲染弹幕， 默认不渲染
        player: null, // 播放器对象
        contextmenu: [
          {
            text: '美菜拥有您想不到的惊喜',
            link: 'https://www.meicai.cn/#/'
          }
        ],
        videoLiveServerDefault: '//media.w3.org/2010/05/sintel/trailer.mp4', // 视频默认的服务地址
        videoLiveServerSpare: '', // 视频关闭切换服务器的过度地址
        videoLiveHlsQualitySpare: '', // 视频关闭切换HLS的过渡地址
        webSocket: {},
        ws: {},
        chatTypeEnum: {
          chat: 0,
          question: 1
        },
        activeChatType: 0, // 默认是聊天
        questionDataIsPull: false, // 是否已经点击过切换提问
        onlinePersonNum: 0,
        videoFormData: {
          newLasted: [], // 最新视频
          carousel: [] // 轮播视频即即热门视频
        },
        videoTypeList: [
          {label: '未开播'}, {label: '正在播放'}, {label: '直播结束'}
        ],
        liveStatusEnum: {
          NotStart: 0,
          Starting: 1,
          End: 2,
          Back: 3
        },
        isBarrage: false, // 是否开启弹幕，默认开启
        heartCheck: {
          timeout: 55000, // 心跳时间
          serverTimeoutObj: null,
          timeoutObj: null,
          onclose_connected_count: 0,
          reset: this.reset,
          start: this.start
        },
        ctxId: '', // netty 全局通道Id
        iEmotion: false, // 是否显示表情
        currentIP: '', // 用户公网IP
        currentTimeOut: 86400000,// 用户公网IP超时时间 默认24 小时超时
        smallFaceSize: 77,
        topFaceIndex: [2, 3],
        requestLimit: {
          isRequestLimit: false,
          reqNum: 0,
          limit: 1, // 访问次数
          timeUnit: 2000 // 单位时间
        }
      }
    },
    components: {
      headerView,
      footerView,
      'd-player': VueDPlayer,
      Emotion
    },
    created () {
    },
    mounted () {
      this.bindListener() // 绑定监听器
      this.init()
    },
    destroyed () {
      window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
      window.removeEventListener('unload', e => this.unloadHandler(e))
    },
    methods: {
      bindListener () {
        window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
        window.addEventListener('unload', e => this.unloadHandler(e))
      },
      init () {
        let _self = this
        _self.initVideoDetail()
          .then((res) => {
            if (_self.videoLiveHlsQualitySpare || _self.liveServer) {
              if (_self.video.liveStatus == _self.liveStatusEnum.Starting || _self.video.liveStatus == _self.liveStatusEnum.NotStart) { // 只有正在直播或者直播未开始的视频才需要连接netty服务器
                _self.initWebSocket(true) // 初始化websockt 对象
                _self.initWsListener() // 初始化websocket 相关监听器
              }
            }
            // danmu(_self)
            _self.initOtherVideo()
            // 加载聊天数据
            _self.initChatData(_self.activeChatType)
            _self.initFace()
          }, (err) => {
            Notification.warning({
              title: '友情提示',
              message: err
            })
          })
      },
      play () {
        console.log('开始播放')
      },
      initFace () { // 初始化表情相关
        var _self = this
        $(document).click(function (e) {
          var _con = $('#emotion-box-id')   // 设置目标区域</span>
          if ($('#biaotitle').is(e.target)) return
          if (!_con.is(e.target) && _con.has(e.target).length === 0) { // Mark 1
            $('#emotion-box-id').hide()
            _self.iEmotion = false
          }
        })
      },
      initVideoDetail () { // 初始化视频详情
        let _self = this
        return new Promise((resolve, reject) => {
          if (_self.video.liveNo == null) {
            Notification.error({
              title: '友情提示',
              message: '直播编号为空,无法正常加载视频！'
            })
            return
          }
          _self.currentIP = localStorage.getExpire('currentIP')
          if (!_self.currentIP) {
            axo.get(process.env.REST_IP).then((res => {
              localStorage.setExpire('currentIP', res.data.body, _self.currentTimeOut)
              console.log('获取到的IP为' + res.data.body)
              _self.doGetVideoDetail(_self, resolve, reject, res.data.body)
            })).catch((e) => {
              reject(e)
            })
          } else {
            _self.doGetVideoDetail(_self, resolve, reject, _self.currentIP)
          }
        })
      },
      doGetVideoDetail (_self, resolve, reject, currentIP) {
        var params = {
          liveNo: _self.video.liveNo,
          ip: currentIP, // 用户公网IP
        }
        videoAPI.getVideoDetail(params, (res) => {
          if (res) {
            if (res.isShelves == 0) {
              reject('当前视频已下架！')
              return
            }
            if (res.isDeleted == 1) {
              reject('当前视频已被删除！')
              return
            }
            _self.video = res
            _self.videoLiveServerSpare = _self.video.liveServer
            if (res.videoHlsDetailList && res.videoHlsDetailList.length == 0) {
              reject('当前视频没有配置HLS流,请联系管理员！')
              return
            }
            _self.renderPlayer(res, _self) // 渲染播放器
            resolve('成功')
          } else {
            reject('当前视频不存在,可能视频配置错误,请联系平台管理员！')
          }
        })
      },
      renderPlayer (res, _self) {
        var qualityArr = []
        var advanceArr = [] // 预告
        var reallyArr = [] ///最终的播放地址
        var playStatus = true
        if (res.liveStatus == _self.liveStatusEnum.NotStart) {
          _self.$message.info('当前直播未开始')
          playStatus = false
          _self.video.liveServer = _self.videoLiveServerDefault
        } else if (res.liveStatus == _self.liveStatusEnum.End) {
          _self.$message.info('当前直播已经结束')
          playStatus = false
          _self.video.liveServer = null
          return
        }

        res.videoHlsDetailList.forEach((ele, index) => {
          var format = ele.liveHlsAddress.split('.')
          var type = format[format.length - 1]
          if (ele.isAdvance == 1) { // 是预告
            _self.switchType(true, type, advanceArr, qualityArr, ele)
          } else {
            _self.switchType(false, type, advanceArr, qualityArr, ele)
          }
        })

        if (!playStatus && advanceArr.size != 0) { // 未开始 并且有预告
          reallyArr = this.playerUrlTimeSheet(advanceArr)
          _self.video.quality = reallyArr

        } else if (!playStatus && advanceArr.size == 0) { // 未开始 没有预告，显示默认片头
          _self.video.quality = defaultHls
        } else { // 已开始
          reallyArr = this.playerUrlTimeSheet(qualityArr)
          _self.video.quality = reallyArr
        }
        if (_self.video.quality.length == 0) { // 最后检查，防止管理端配置错误
          Notification.error({
            title: '友情提示',
            message: '没有配置HLS流，请联系管理员！'
          })
          return
        }
        _self.videoLiveHlsQualitySpare = qualityArr // 暂存，为了切换视频
        _self.dplayerFlag = true // dplayer渲染
        if (res.liveStatus == 1) {
          _self.video.live = true
        } else {
          _self.video.live = false
        }
        _self.video.pic = (res.liveCenterImg != undefined ? res.liveCenterImg : '') // 视频封面
        _self.$nextTick(function () {
          _self.player = _self.$refs.player.dp
          // 因为在Dplayer 内部无法获取到vue的对象，通过window对象传递
          window.$$$video = {}
          window.$$$video.sendChat = _self.sendChat
        })
      },
      switchType (isAdvance, type, advanceArr, qualityArr, ele) {
        if (type == 'm3u8') {
          type = 'hls'
        } else if (type == 'flv') {
          type = 'flv'
        } else {
          type = 'auto'
        }
        if (isAdvance) {
          advanceArr.push({
            url: ele.liveHlsAddress,
            name: ele.liveHlsType,
            type: type
          })
        } else {
          qualityArr.push({
            url: ele.liveHlsAddress,
            name: ele.liveHlsType,
            type: type
          })
        }
      },
      // 播放地址按照时间戳规则打散
      playerUrlTimeSheet (playerUrlArr) {
        var currentTime = new Date().getTime()
        var mappUrl = []
        if (currentTime % 2 == 0) {
          for (var i = playerUrlArr.length - 1; i >= 0; i--) {
            mappUrl.push(playerUrlArr[i])
          }
          return mappUrl
        } else {
          return playerUrlArr
        }
      },
      initChatData (activeType) { // 初始化聊天数据
        let _self = this
        var params = {
          videoId: this.video.id,
          chatType: activeType // 默认聊天信息
        }
        chatAPI.getChatList(params, (res) => {
          if (res) {
            var chatStr = ''
            for (let index in res) {
              var chat = res[index] // 每个chat
              chatStr += this.buildChatMessage(chat, chatStr, _self)
            }
            // 将初始化获得的聊天信息传至弹幕
            if (_self.danmuInit) {
              _self.beautifyDanMu(res, _self)
            }
            if (activeType == _self.chatTypeEnum.chat) {
              $('#words_chat').append(chatStr)
              _self.scrollToBottom(0)
            } else {
              $('#words_question').append(chatStr)
            }
          }
        })
      },
      beautifyDanMu (res, _self) { // 美化弹幕加载
        var danmaku = _self.getDammuObject()
        var count = 1
        _self.$nextTick(function () {
          var clear = setInterval(() => {
            if (res[count] != undefined) {
              danmaku.text = res[count].content
              _self.player.danmaku.draw(danmaku)
              count++
            } else {
              clearInterval(clear)
            }
          }, Math.random())
        })
      },
      initWebSocket (begin) { // 初始化websocket连接
        var _self = this
        if (!window.WebSocket) {
          window.WebSocket = window.MozWebSocket
        }
        if (window.WebSocket) {
          this.webSocket = new WebSocket(process.env.NETTY_SERVER)
          this.webSocket.onmessage = function (event) {
            _self.heartCheck.reset().start() // 如果获取到消息，说明连接是正常的，重置心跳检测
            var json = JSON.parse(event.data)
            if (json.status == 200) {
              var type = json.data.type
              console.log('收到一条新信息，类型为：' + type)
              switch (type) {
                case 'CONNECTED':
                  _self.ws.connectedReceive(json.data)
                  break
                case 'GROUP_SENDING':
                  _self.ws.groupReceive(json.data)
                  break
                case 'LIVE_SERVER':
                  _self.ws.liveServerReceive(json.data)
                  break
                case 'NOTICE': // pong do nothing
                  _self.ws.onlineNotice(json.data)
                  console.log('收到在线人数')
                  break
                case 'PONG': // pong do nothing
                  console.log('收到消息PONG')
                  break
                default:
                  console.log('不正确的类型！')
              }
            } else {
              alert(json.msg)
              console.log(json.msg)
            }
          }
          // 连接成功1秒后，将用户信息注册到服务器在线用户表
          this.webSocket.onopen = function () {
            _self.heartCheck.reset().start()
            setTimeout(function (event) {
              if (begin) {
                Notification.success({
                  title: '友情提示',
                  message: '客户端连接成功,您可以跟主播互动了哦！'
                })
              }
              _self.ws.connected()
            }, 1000)
          }
          this.webSocket.onclose = function (event) {
            Notification.warning({
              title: '抱歉',
              message: '客户端失去连接...请刷新界面重新连接！'
            })
          }
          // 连接发生错误，连接错误时会继续尝试发起连接（尝试5次）
          this.webSocket.onerror = function () {
            Notification.error({
              title: '抱歉',
              message: '聊天服务器无法连接！请联系管理员！'
            })
          }
        } else {
          Notification.warning({
            title: '抱歉',
            message: '您的浏览器不支持聊天服务, 请换用谷歌浏览器继续访问！'
          })
        }
      },
      start () { // 前端ws重试机制，目前未采取
        var _self = this
        this.heartCheck.timeoutObj = setInterval(function () {
          if (_self.webSocket.readyState == 1) {
            console.log('连接状态，发送消息PING保持连接')
            var ping = {
              type: 'PING',
              videoId: _self.video.id,
              createUserCode: _self.loginUser.uid
            }
            _self.webSocket.send(JSON.stringify(ping))
          } else {
            console.error('websocket连接异常，正在尝试重新加载websocket')
            _self.initWebSocket(false)
          }
        }, _self.heartCheck.timeout)
      },
      reset () {
        clearTimeout(this.heartCheck.timeoutObj)
        return this
      },
      initWsListener () { // 初始化wesocket监听对象
        var _self = this
        this.ws = {
          connected: function () {
            if (!window.WebSocket) {
              Notification.warning({
                title: '友情提示',
                message: '当前浏览器不支持！请换用谷歌浏览器继续浏览'
              })
              return
            }
            if (_self.webSocket.readyState == WebSocket.OPEN) {
              var data = {
                'userId': _self.loginUser.uid,
                'videoId': _self.video.id,
                'liveNo': _self.video.liveNo,
                'type': 'CONNECTED'
              }
              _self.webSocket.send(JSON.stringify(data))
            } else {
              Notification.warning({
                title: '友情提示',
                message: '聊天服务器没有开启！请刷新页面重试！'
              })
            }
          },
          groupSend: function (data) {
            // 下面注释掉的是聊天服务器单节点时的代码，使用MQ消息机制集群方案解决单节点问题
            /* if (!window.WebSocket) {
                      return
                    }
                    if (_self.webSocket.readyState == WebSocket.OPEN) {
                      data.type = 'GROUP_SENDING'
                      _self.webSocket.send(JSON.stringify(data))
                    } else {
                      Notification.warning({
                        title: '友情提示',
                        message: '聊天服务器没有开启！'
                      })
                    } */
            // netty 服务器集群方案
            // _self.socketSendByMq(data)
          },
          connectedReceive: function (responseData) {
            _self.ctxId = responseData.ctxId
          },
          groupReceive: function (chat) {
            var chatStr
            if (chat.chatType == _self.chatTypeEnum.chat) { // 聊天
              chatStr = _self.buildChatMessage(chat, chatStr, _self)
              $('#words_chat').append(chatStr)
              _self.scrollToBottom(0)
            } else { // 提问
              chatStr = _self.buildChatMessage(chat, chatStr, _self)
              $('#words_question').append(chatStr)
              _self.scrollToBottom(1)
            }
            _self.playerDanMuDraw(chat.content, _self)
          },
          liveServerReceive (data) {
            if (data.content == 'close') {
              Notification.warning({
                title: '友情提示',
                message: '当前直播已被关闭！'
              })
              _self.closeOrOpenLive('close', _self)
            } else {
              Notification.success({
                title: '友情提示',
                message: '直播开启！'
              })
              _self.closeOrOpenLive('open', _self)
            }
          },
          onlineNotice (data) {
            _self.onlinePersonNum = data.onlineUserNum
          }
        }
      },
      initOtherVideo () { // 加载其它视频
        var _self = this
        var param = {
          isDetail: true
        }
        videoAPI.getOtherVideoOfDetailPage(param, res => {
          if (res) {
            res.forEach((el, index) => {
              el.liveStatusName = _self.videoTypeList[el.liveStatus].label
            })
            _self.videoFormData.newLasted = res
          }
        })
      },
      closeOrOpenLive (flag, _self) { // 监听后台关闭或者开启直播的事件
        if (flag == 'open') {
          _self.video.liveServer = _self.videoLiveServerSpare
          _self.video.quality = _self.videoLiveHlsQualitySpare
        } else {
          _self.video.liveServer = null
          _self.video.quality = defaultHls
        }
        window.location.reload()
      },
      handleClick (tab, event) { // 聊天/提问切换
        if (!this.questionDataIsPull) {
          this.initChatData(this.chatTypeEnum.question)
          this.questionDataIsPull = true
        }
      },
      buildChatMessage (chat, chatStr, _self) {
        if (chat == undefined) return
        if (chat.createUserCode == _self.loginUser.uid) {
          chatStr = '<div class="me row">' +
            '<div class="chat_message me_10 col-sm-10">' +
            '<div class = "nameTitle">' + _self.loginUser.username + '-' + _self.loginUser.uid + '</div>' +
            '<div class = "me_chat_content">' + chat.content + '</div></div>' +
            '<div class="chat-avatars col-sm-2">' + _self.loginUser.username.substring(1) + '</div>' +
            '</div>'
        } else {
          chatStr = '<div class="other_chat row">' +
            '<div class="col-md-2 col-xs-2 col-sm-2 other_col" ><span class="chat-avatars_other">' + chat.createUserName.substring(1) + '</span></div>' +
            '<div class = "col-md-10 col-xs-10  col-sm-10 other_10">' +
            '<div class = "nameTitle">' + chat.createUserName + '-' + chat.createUserCode + '</div>' +
            '<div class = "other_chat_content">' + chat.content + '</div>' +
            '</div>' +
            '</div>'
        }
        if (_self.isBarrage) {
          setTimeout(() => {
            _self.$$createEle(chat.content)
          }, Math.random() * 30000)
        }
        return _self.emotion(chatStr)
      },
      sendChat (danmu) { // 发送聊天 参数是弹幕输入的信息
        var messageStr = ''
        var _self = this
        if (!_self.sendMessagePreCheck(_self)) return // 发送信息之前的检查操作

        if (danmu && danmu != '') {
          messageStr = danmu
        } else {
          messageStr = _self.chatMessage
          _self.playerDanMuDraw(messageStr, _self)
        }

        // 如果输入的数据为空，则弹窗友情提示
        if (messageStr === '') {
          Notification.warning({
            title: '友情提示',
            message: '请输入聊天内容'
          })
          return
        }
        var chatData = {
          // createUserCode: _self.loginUser.uid,
          // createUserName: _self.loginUser.username,
          videoId: _self.video.id,
          content: messageStr,
          chatType: _self.chatTypeEnum.chat,
          ctxId: _self.ctxId,
          liveNo: _self.video.liveNo
        }
        var callback = function (chatData, _self) {
          var str = '<div class="me row">' +
            '<div class="chat_message me_10 col-sm-10">' +
            '<div class = "nameTitle">' + _self.loginUser.username + '-' + _self.loginUser.uid + '</div>' +
            '<div class = "me_chat_content">' + chatData.content + '</div>' +
            '</div>' +
            '<div class="chat-avatars col-sm-2">' + _self.loginUser.username.substring(1) + '</div>' +
            '</div>'

          $('#words_chat').append(_self.emotion(str))
          _self.chatMessage = ''
          _self.scrollToBottom(0)
          // 将聊天数据推送到websocket
          // _self.ws.groupSend(chatData)
        }
        // 将聊天数据推送到live 后台
        _self.sendChatToBackend(chatData, callback, _self)
      },
      sendChatToBackend (chatData, callback, _self) { // 将聊天推送到服务器
        if (this.requestLimitFunc()) {
          return
        }

        chatAPI.addChat(chatData, (res) => {
          // do nothing
          if (res == 1 && callback) { // 只有满足提问次数才能提问
            callback(chatData, _self)
          }
        })
      },
      requestLimitFunc () {
        if (!this.requestLimit.isRequestLimit) {
          setInterval(() => {
            this.requestLimit.reqNum = 0
          }, this.requestLimit.timeUnit)
        }
        if (this.requestLimit.reqNum >= this.requestLimit.limit) {
          Notification.info({
            title: '友情提示',
            message: '您的消息发送过于频繁！'
          })
          return true
        }
        this.requestLimit.reqNum++
        this.requestLimit.isRequestLimit = true
        return false
      },
      sendMessagePreCheck (_self) {
        if (_self.video.liveServer == null) {
          Notification.warning({
            title: '友情提示',
            message: '直播结束啦！请不要聊天哦!'
          })
          _self.chatMessage = ''
          return false
        }
        if (_self.webSocket.readyState != WebSocket.OPEN) {
          Notification.warning({
            title: '友情提示',
            message: '聊天服务器没有连接成功，请刷新重新连接!'
          })
          return false
        }
        return true
      },
      sendQuestion () {
        var _self = this
        if (this.answerMessage === '') {
          Notification.warning({
            title: '友情提示',
            message: '请输入提问内容'
          })
          return
        }
        if (!_self.sendMessagePreCheck(_self)) return

        var chatData = {
          // createUserCode: _self.loginUser.uid,
          // createUserName: _self.loginUser.username,
          videoId: _self.video.id,
          content: _self.answerMessage,
          chatType: _self.chatTypeEnum.question,
          ctxId: _self.ctxId,
          liveNo: _self.video.liveNo
        }
        // 回调函数
        var callback = function (chatData, _self) {
          var str = '<div class="me row">' +
            '<div class="chat_message  me_10 col-sm-10">' +
            '<div class = "nameTitle">' + _self.loginUser.username + '-' + _self.loginUser.uid + '</div>' +
            '<div class = "me_chat_content">' + _self.answerMessage + '</div>' +
            '</div>' +
            '<div class="chat-avatars col-sm-2">' + _self.loginUser.username.substring(1) + '</div>' +
            '</div>'
          $('#words_question').append(_self.emotion(str))
          if (_self.isBarrage) {
            _self.$$createEle(_self.answerMessage)
          }
          _self.answerMessage = ''
          _self.scrollToBottom(1)
          // _self.ws.groupSend(chatData)
        }
        // 将聊天数据推送到live 后台
        _self.sendChatToBackend(chatData, callback, _self)
      },
      beforeunloadHandler () { // 浏览器关闭
        this._beforeUnload_time = new Date().getTime()
      },
      unloadHandler (e) {
        this._gap_time = new Date().getTime() - this._beforeUnload_time
        if (this._gap_time <= 5) {
          var parasm = {
            liveNo: this.video.liveNo,
            uid: this.loginUser.uid
          }
          // todo   不处理用户离开
          // videoAPI.userAway(parasm, res => {
          // })
        }
      },
      scrollToBottom (type) {
        debugger
        var idArr = ['#words_chat', '#words_question']
        $(idArr[type]).scrollTop($(idArr[type])[0].scrollHeight)
      },
      toDetail (row) {
        // 传值
        this.$router.push({path: '/detail', query: {liveNo: row.liveNo}})
      },
      socketSendByMq (message) {
        chatAPI.socketSendByMq(message, res => {
        })
      },
      socketRemoveByMq (message) {
        chatAPI.socketRemoveByMq(message, res => {
        })
      },
      getDammuObject () {
        return {
          color: '#fff',
          type: 'right',
          time: new Date().getTime()
        }
      },
      playerDanMuDraw (messageStr, _self) { // 绘制弹幕
        var danmu = _self.getDammuObject()
        danmu.text = _self.emotion(messageStr)
        _self.player.danmaku.draw(danmu)
      },
      // 表情相关
      toggloEmotion () { // 切换表情下拉框
        this.iEmotion = !this.iEmotion
      },
      handleEmotion (i) { // 选择表情
        if (this.activeName === 'chat') { // 提问
          this.chatMessage += '$' + i + '$'
        } else {
          this.answerMessage += '$' + i + '$'
        }
      },
      // 将匹配结果替换表情图片
      emotion (res) { // 渲染表情
        var str = ''
        let word = res.replace(/\#|\;/gi, '')
        const list = emotionList // 表情数组
        var arr = word.split('$')
        var time = new Date().getTime()
        for (let i = 0; i < arr.length; i++) {
          let index = list.indexOf(arr[i])
          if (index !== -1) {
            if (index == 2) {
              str += `<img style="height: 70px;" src="https://img-oss.yunshanmeicai.com/infocube/emotion/${index}.gif?time=" + ${time}  align="middle">`
            } else if (index > this.smallFaceSize || this.topFaceIndex.indexOf(index) != -1) {
              str += `<img style="width:70px;height: 70px;" src="https://img-oss.yunshanmeicai.com/infocube/emotion/${index}.gif?time=" + ${time}  align="middle">`
            } else {
              str += `<img src="https://img-oss.yunshanmeicai.com/infocube/emotion/${index}.gif?time=" + ${time} align="middle">`
            }
          } else {
            str += arr[i]
          }
        }
        return str
      }
    },
    computed: {}

  }
</script>
<style>

  @media only screen and (min-width: 992px) {
    .dplayer-div {
      height: 556px;
    }

    .talk_show {
      height: 400px;
    }

    .emotionChat {
      right: 33%;
    }

    .col-md-2 {
      width: 20%;
    }

    .col-sm-10 {
      width: 80%;
    }

    .el-input__inner {
      padding-right: 35%;
    }
  }

  @media (min-width: 768px) and  (max-width: 992px) {
    .col-md-2 {
      width: 10% !important;
    }

    .col-sm-10 {
      width: 90% !important;;
    }

    .emotionChat {
      right: 16%;
    }

    .el-input__inner {
      padding-right: 9%;
    }

    .talk_con {
      height: 800px;
      overflow-y: scroll;
    }

    .talk_show {
      height: calc(42vh);
    }

    .phoneStyle {
      padding-left: 3px!important;
      padding-right: 0px!important;
    }
  }

  @media only screen and (min-width: 1900px) {
    .dplayer-div {
      height: 656px;
    }

    .talk_show {
      height: 500px;
    }

    .emotionChat {
      right: 23%;
    }

    .col-md-2 {
      width: 13.66666667%;
    }

    .col-sm-10 {
      width: 85.33333333%
    }

    .el-input__inner {
      padding-right: 20%;
    }
  }


  .container {
    width: 85% !important;
  }

  .talk_show {
    /*height: calc(55vh);*/
    padding-right: 10px;
    overflow-y: scroll;
    overflow-x: hidden;
  }

  .other_chat_div {

  }

  .talk_sub {
    position: relative;
    top: 10px;
    left: 4px;
  }

  .me {
    text-align: right;
  }

  @media screen and (max-width: 1000px) {
    .wrap-vid img {
      height: 230px;
    }

  }

  .chat-avatars {
    display: inline-block;
    width: 50px !important;
    height: 50px;
    border-radius: 50%;
    background: #eee;
    vertical-align: top;
    overflow: hidden;
    line-height: 50px;
    text-align: center;
    background: #1e9fff !important;
    color: #fff;
    top: 10px;
  }

  .nameTitle {
    color: #989A9C;
  }

  .chat-avatars_other {
    display: inline-block;
    width: 50px !important;
    height: 50px;
    border-radius: 50%;
    background: #eee;
    vertical-align: top;
    overflow: hidden;
    line-height: 50px;
    text-align: center;
    background: #1e9fff !important;
    color: #fff;
    position: relative;
    top: 10px;

  }

  .other_chat_content {
    padding-left: 70px;
    background: white;
    min-height: 36px;
    max-width: 252px;
    text-align: left;
    padding: 4px 12px;
    border-radius: 6px;
    word-wrap: break-word;
    display: inline-block;
    position: relative;
    margin-bottom: 10px;
  }

  .other_chat_content:before {
    position: absolute;
    content: "";
    top: 8px;
    left: -6px;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid white;

  }

  .me_chat_content {
    background: white;
    color: black;
    text-align: left;
    min-height: 36px;
    max-width: 252px;
    text-align: left;
    padding: 4px 12px;
    border-radius: 6px;
    word-wrap: break-word;
    display: inline-block;
    position: relative;
  }

  .me_chat_content:before {
    position: absolute;
    content: "";
    top: 8px;
    right: -6px;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid white;
  }

  .wrap .box {
    position: relative;
    width: 100%;
    height: 90%;
  }

  .wrap .box span {
    position: absolute;
    top: 10px;
    left: 20px;
    display: block;
    padding: 10px;
    color: #336688
  }

  .wrap .send .send-btn:hover {
    background-color: #4cacdc
  }

  #page-content {
    background-color: #232527; /* 浏览器不支持时显示 */
  }

  .container_detail {
    background-image: linear-gradient(#419bf9, #ffffff);
    border-radius: 10px;
  }

  .el-tabs {
    background-image: linear-gradient(#264968, #505e66);
  }

  .el-tabs--border-card > .el-tabs__header {
    background-color: #1f2124
  }

  .el-tabs__content {
    color: black;
  }

  .el-tabs--border-card {
    border: 0px;
  }

  #tab-chat {
    font-size: 20px;
    font-weight: bold;
    font-family: monospace;
    margin: 10px 0px 10px 0px;
  }

  #tab-question {
    font-size: 20px;
    font-weight: bold;
    font-family: monospace;
    margin: 10px 0px 10px 0px;
  }

  .el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active {
    background-color: #1f2124;
    border-right-color: #1f2124;
    border-left-color: #1f2124;
  }

  .el-tabs--border-card > .el-tabs__header .el-tabs__item {
    background-color: #1f2124;
    border-right-color: #1f2124;
    border-left-color: #1f2124;
  }

  .el-tabs--border-card > .el-tabs__header {
    border-bottom: 0px;
  }

  .el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active {
    color: white;
  }

  .emotionChat {
    position: absolute;
    width: 50px;
    top: 4px;
  }

  .talk_input {
    margin-top: 5px;
  }

  /*********************************/

  .banseo {
    width: 728px;
    top: 36px;
  }

  .el-input__inner {
    width: 85%;
    height: 60px;
    opacity: 1;
    background-color: #eceff1;
    border-radius: 5px 0px 0px 5px;
    border: 0px;
    font-size: 20px;
    color: #673ab7;
    outline: none;
    background-image: linear-gradient(to right, #9e9e9e36, #f7f4f4);
  }

  .banbutt {
    height: 60px;
    width: 80px;
    background-color: #1890ff;
    border: 0px;
    color: #fff;
    border-top-left-radius: 0px;
    border-bottom-left-radius: 0px;
    transition: all .7s ease 0s;
    font-size: 15px;
    background: #1890ff
  }

  .banbutt:hover {
    background-color: #ed3800;
    background: #1890ff
  }

  .seoicn {
    position: absolute;
    left: 20px;
    bottom: -75px;
    color: #b0bec5;
    font-size: 18px
  }

  .button, input, optgroup, select, textarea {
    margin: 0;
    font: inherit;
  }

  .button, input, select, textarea {
    font-family: monospace;
    font-size: inherit;
    line-height: inherit;
  }

  .bantxt {
    position: absolute;
  }

  .banbutt {
    position: absolute;
    right: 20px;
  }

  .messageRow {
    height: 20px;
  }

</style>
